package com.eqdd.yiqidian.ui.gongneng.kehu.fragment;

import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.databinding.ViewDataBinding;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;

import com.arlib.floatingsearchview.FloatingSearchView;
import com.arlib.floatingsearchview.suggestions.model.SearchSuggestion;
import com.eqdd.yiqidian.CustomerManageFragmentCustom;
import com.eqdd.yiqidian.R;
import com.eqdd.yiqidian.SearchCoolRefreshRecyclerViewFragmentCustom;
import com.eqdd.yiqidian.adapter.recycleadapter.ItemClickSupport;
import com.eqdd.yiqidian.adapter.slimadapter.SlimAdapterEx;
import com.eqdd.yiqidian.adapter.slimadapter.SlimInjector;
import com.eqdd.yiqidian.adapter.slimadapter.viewinjector.IViewInjector;
import com.eqdd.yiqidian.base.AppConstent;
import com.eqdd.yiqidian.base.BaseActivity;
import com.eqdd.yiqidian.base.BaseFragment;
import com.eqdd.yiqidian.base.Config;
import com.eqdd.yiqidian.bean.rebuild.HuifangRecordListResultBean;
import com.eqdd.yiqidian.bean.rebuild.ZhangPageResultBean;
import com.eqdd.yiqidian.box.ItemDecoration.DividerLineItemDecoration;
import com.eqdd.yiqidian.helper.mvchelper.ModelRx2DataSource;
import com.eqdd.yiqidian.helper.mvchelper.Rx2DataSource;
import com.eqdd.yiqidian.http.DialogCallBack;
import com.eqdd.yiqidian.http.HttpConfig;
import com.eqdd.yiqidian.http.HttpResult;
import com.eqdd.yiqidian.http.JsonConverter;
import com.eqdd.yiqidian.ui.gongneng.kehu.HuifangRecordInfoActivity;
import com.eqdd.yiqidian.utils.GreenDaoUtil;
import com.eqdd.yiqidian.utils.SwipeUtil;
import com.eqdd.yiqidian.utils.ToastUtil;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.lzy.okrx2.adapter.FlowableBody;
import com.shizhefei.mvc.MVCCoolHelper;
import com.shizhefei.mvc.MVCSwipeRefreshHelper;

import org.reactivestreams.Publisher;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.Flowable;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Function;

/**
 * Created by lvzhihao on 17-5-24.
 */

public class VisitRecordFragment extends BaseFragment {
    CustomerManageFragmentCustom dataBinding;
    private SlimAdapterEx<HuifangRecordListResultBean> slimAdapterEx;
    private String cusid;
    private String clientName;
    private int pageNum;
    private ModelRx2DataSource<HuifangRecordListResultBean> dataSource;
    private MVCSwipeRefreshHelper<List<HuifangRecordListResultBean>> mvcHelper;


    @Override
    protected void setView() {

    }

    @Override
    public void loadData() {
    }


    @Override
    protected void initData() {
        if (slimAdapterEx == null) {
            cusid = getArguments().getString("cusid");
            clientName = getArguments().getString(Config.CLIENT_NAME);
            dataBinding.recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
            dataBinding.recyclerView.addItemDecoration(new DividerLineItemDecoration(getActivity()));
            slimAdapterEx = SlimAdapterEx.create().register(R.layout.list_item_141, new SlimInjector<HuifangRecordListResultBean>() {
                @Override
                public void onInject(HuifangRecordListResultBean data, IViewInjector injector) {
                    injector.text(R.id.tv_right_center_content, data.getContactsName())
                            .text(R.id.tv_upper_left_content, data.getRevisitTitle())
                            .text(R.id.tv_down_left_content, data.getRevisitDate());
                }
            }).attachTo(dataBinding.recyclerView).updateData(new ArrayList());

            ItemClickSupport.addTo(dataBinding.recyclerView)
                    .setOnItemClickListener((recyclerView, position, v) -> {
                        Intent intent = new Intent(getActivity(), HuifangRecordInfoActivity.class);
                        intent.putExtra("revisitRecordid", slimAdapterEx.getDataItem(position).getId() + "");
                        intent.putExtra(Config.CLIENT_NAME, clientName);
                        intent.putExtra("cusid", cusid);
                        getActivity().startActivityForResult(intent, position);
                    })
                    .setOnItemLongClickListener((recyclerView, position, v) -> {
                        new AlertDialog.Builder(getActivity())
                                .setTitle("提示")
                                .setMessage("是否删除" + slimAdapterEx.getDataItem(position).getContactsName() + "?")
                                .setCancelable(true)
                                .setPositiveButton("确定", (dialog, which) -> {
                                    dialog.dismiss();
                                    delete(slimAdapterEx.getDataItem(position).getId(), position);

                                })
                                .setNegativeButton("退出", (dialog, which) -> {
                                            dialog.dismiss();
                                        }
                                )
                                .create()
                                .show();

                        return true;

                    });
            dataSource = new ModelRx2DataSource<>(new ModelRx2DataSource.OnLoadSource() {
                @Override
                public Flowable<List> loadSource(int page, Rx2DataSource.DoneActionRegister register) {
                    pageNum = page == 1 ? 0 : pageNum;
                    return OkGo.<ZhangPageResultBean<List<HuifangRecordListResultBean>>>post(HttpConfig.BASE_URL + HttpConfig.HUIFANG_RECORD_LIST)
                            .params("page", pageNum)
                            .params("getpeople", 0)
                            .params("owner", AppConstent.user.getGuid())
                            .params("comid", AppConstent.user.getCompanyId())
                            .params("cusid", cusid)
                            .converter(new JsonConverter<ZhangPageResultBean<List<HuifangRecordListResultBean>>>() {
                                @Override
                                public void test() {
                                    super.test();
                                }
                            }).adapt(new FlowableBody<ZhangPageResultBean<List<HuifangRecordListResultBean>>>())
                            .flatMap(new Function<ZhangPageResultBean<List<HuifangRecordListResultBean>>, Publisher<List<HuifangRecordListResultBean>>>() {
                                @Override
                                public Publisher<List<HuifangRecordListResultBean>> apply(@NonNull ZhangPageResultBean<List<HuifangRecordListResultBean>> noticeWraperResultBeanHttpResult) throws Exception {
                                    if (page == 1) {
                                        mvcHelper.setAutoLoadMore(true);
                                    }
                                    pageNum = noticeWraperResultBeanHttpResult.getNextpage();
                                    return Flowable.just(noticeWraperResultBeanHttpResult.getItems() == null ? new ArrayList() : noticeWraperResultBeanHttpResult.getItems());
                                }
                            });

                }
            }, 10);
            mvcHelper = new MVCSwipeRefreshHelper<List<HuifangRecordListResultBean>>(dataBinding.swipeLayout);
            mvcHelper.setDataSource(dataSource);
            mvcHelper.setAdapter(slimAdapterEx);
            mvcHelper.refresh();

        }
    }

    private void delete(int id, int position) {
        OkGo.<HttpResult>post(HttpConfig.BASE_URL + HttpConfig.KEHU_DELETE_HUIFANG_RECORD)
                .params("owner", GreenDaoUtil.getUser().getGuid())
                .params("revisitRecordid", id)
                .execute(new DialogCallBack<HttpResult>((BaseActivity) getActivity()) {
                    @Override
                    public void onSuccess(Response<HttpResult> response) {
                        HttpResult httpResult = response.body();
                        ToastUtil.showShort(httpResult.getMsg());
                        if (httpResult.getStatus() == 200) {
                            slimAdapterEx.getData().remove(position);
                            slimAdapterEx.notifyItemRemoved(position);
                        }
                    }
                });
    }


    @Override
    public ViewDataBinding initBinding(LayoutInflater inflater) {
        return dataBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_customer_manage, null, false);
    }

    @Override
    public void onClick(View v) {

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Config.SUCCESS) {
            if (requestCode == Config.ADD_HUIFANG_RECORD) {
                mvcHelper.refresh();
            } else {
                HuifangRecordListResultBean bean = (HuifangRecordListResultBean) data.getSerializableExtra("bean");
                slimAdapterEx.getData().remove(requestCode);
                slimAdapterEx.getData().add(requestCode, bean);
                slimAdapterEx.notifyItemChanged(requestCode);
            }
        }
    }
}
